package com.elitesland.security.rest;

import cn.hutool.core.util.IdUtil;
import com.elitesland.core.base.ApiResult;
import com.elitesland.core.util.RedisUtils;
import com.elitesland.security.config.bean.JwtProperties;
import com.elitesland.security.config.bean.LoginProperties;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <pre>
 * 认证相关信息的接口，如Captcha图片的生成
 * </pre>
 *
 * @author Mir
 * @date 2020/6/21
 */
@RestController
@RequestMapping("/sec")
@Api(value = "安全相关的接口", tags = {"系统安全"})
@RequiredArgsConstructor
public class SecurityController {

    private final JwtProperties properties;
    private final LoginProperties loginProperties;
    private final RedisUtils redisUtils;

    @GetMapping("/captcha")
    @ApiOperation("获取验证码图片，和缓存标识的UUID")
    public ApiResult<Object> getCaptcha() {
        // 获取运算的结果
        Captcha captcha = loginProperties.getCaptcha();
        String uuid = properties.getCodeKey() + IdUtil.simpleUUID();
        // 保存
        redisUtils.set(uuid, captcha.text(), loginProperties.getCaptchaInfo().getExpiration(), TimeUnit.MINUTES);
        // 验证码信息
        val imgResult = new HashMap<String, Object>(2) {
            private static final long serialVersionUID = -856648464071963590L;

            {
                put("img", captcha.toBase64());
                put("uuid", uuid);
            }
        };
        return ApiResult.ok(imgResult);
    }

    @GetMapping("/capkey/{uuid}")
    @ApiOperation("Captcha的UUID对应key")
    public ApiResult<String> getKey(@PathVariable("uuid") String uuid) {
        val o = redisUtils.get(uuid);
        return ApiResult.ok(o.toString());
    }
}
